<template>
  <div
    class="message-center-container"
    v-if="msgBoxVisible"
  >
    <template>
      <div class="message-center-header">
        <span>{{ $t('message.unreadMessage') }}</span>
        <i
          class="iconfont iconguanbi-01"
          @click="closeBox"
        ></i>
      </div>

      <div class="message-center-box scroll-bar">
        <ul
          class="message-center-list"
          v-if="unreadMsgData.length"
        >
          <li
            v-for="(item, index) in unreadMsgData"
            :key="item.id"
            @click="showMsgDetailBox(item, index)"
          >
            <div class="message-type-time-box">
              <div class="message-type-box">
                <span :class="getMsgTypeClass(item.type)"></span>
                {{ getMsgType(item.type) }}
              </div>
              <div class="message-time-box">{{ formatDate(item.created_date) }}</div>
            </div>
            <p class="message-text-box">{{ item.content }}</p>
          </li>
        </ul>

        <div
          class="no-data-box"
          v-if="showNoDataBox"
        >
          <img
            src="@/assets/images/msg_empty.png"
            alt="msg"
          >
          <p>{{ $t('message.noMessageHint') }}</p>
        </div>
      </div>

      <div class="message-center-footer">
        <button
          class="message-center-btn active"
          @click="jumpMsgCenter"
        >{{ $t('message.enterMessageCenter') }}</button>
        <button
          class="message-center-btn"
          v-if="unreadMsgData.length"
          @click="clearUnreadMsg"
        >{{ $t('message.clearUnreadMessages') }}</button>
      </div>
    </template>

    <div
      class="message-detail-dialog"
      v-if="showMsgDetail"
    >
      <div class="message-detail-dialog-container">
        <div class="detail-dialog-header">
          <div class="header-title">{{ $t('message.messageDetails') }}</div>
          <div class="header-close">
            <i
              class="iconfont iconguanbi-01"
              @click="closeDialogBox"
            ></i>
          </div>
        </div>
        <div class="detail-dialog-body">
          <div class="detail-dialog-body-header">
            <p>{{ msgDetail.title }}</p>
            <span>{{ formatDate(msgDetail.created_date) }}</span>
          </div>
          <div class="detail-dialog-body-content">
            {{ msgDetail.content }}
          </div>
        </div>
        <div class="detail-dialog-footer">
          <div class="operate-btn">
            <el-button
              type="text"
              :disabled="prevDisabled"
              @click="prevFn"
            >{{ $t('message.prev') }}</el-button>
            <el-button
              type="text"
              :disabled="nextDisabled"
              @click="nextFn"
            >{{ $t('message.next') }}</el-button>
          </div>
          <el-button
            size="medium"
            @click="closeDialogBox"
          >{{ $t('operate.close') }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { messageList, messageDetail, clearUnreadMessage } from '@/api/message';

export default {
  name: 'MessageCenter',
  props: {
    msgBoxVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      unreadMsgData: [], //未读消息
      pageIndex: 0, //当前页
      pageSize: 50, //每页显示数据条数
      totalNum: 0, //数据总条数
      isLoadAll: false, //是否已加载全部数据
      timer: '', //定时器
      showNoDataBox: false, //显示无数据样式
      showMsgDetail: false, //显示消息详情
      msgDetail: '', //消息详情
      currentDetailDataIndex: 0, //当前消息详情的下标
      prevDisabled: true, //上一条是否可点击
      nextDisabled: true //下一条是否可点击
    };
  },
  mounted() {
    this.getMsgList();
  },
  methods: {
    // 获取未读信息列表
    getMsgList(hideLoading = false) {
      messageList(
        {
          status: 0,
          limit: this.pageSize,
          offset: this.pageIndex
        },
        hideLoading
      )
        .then(res => {
          this.unreadMsgData = this.unreadMsgData.concat(res.data.list);
          this.totalNum = res.data.total;
          if (this.totalNum === 0) {
            this.showNoDataBox = true;
          }
        })
        .then(() => {
          if (this.unreadMsgData.length > 0) {
            this.scrollFn();
          }
        });
    },
    // 防抖
    debounce(fn, delay = 300) {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }

      this.timer = setTimeout(() => {
        fn();
      }, delay);
    },
    // 监听滚动事件
    scrollFn() {
      let messageBox = document.querySelector('.message-center-box');
      messageBox.addEventListener('scroll', () => {
        this.debounce(() => {
          const scrollTop = messageBox.scrollTop;
          const clientHeight = messageBox.clientHeight;
          const scrollHeight = messageBox.scrollHeight;
          if (scrollTop + clientHeight >= scrollHeight) {
            if (!this.isLoadAll) {
              this.loadMore();
            }
          }
        });
      });
    },
    // 加载更多
    loadMore() {
      if (this.unreadMsgData.length < this.totalNum) {
        this.pageIndex++;
        this.getMsgList(true);
      } else {
        // 已加载全部数据
        this.isLoadAll = true;
      }
    },
    // 生成信息类型对应的类名
    getMsgTypeClass(type) {
      let typeClass = 'msg-default';
      if (type === 2) {
        typeClass = 'msg-warning';
      } else if (type === 5) {
        typeClass = 'msg-danger';
      }
      return typeClass;
    },
    // 生成消息类型
    getMsgType(type) {
      let typeText = '';
      switch (type) {
        case 1:
          typeText = this.$t('message.type.notice');
          break;
        case 2:
          typeText = this.$t('message.type.warning');
          break;
        case 3:
          typeText = this.$t('message.type.prompt');
          break;
        case 4:
          typeText = this.$t('message.type.letter');
          break;
        case 5:
          typeText = this.$t('message.type.alarm');
          break;
      }
      return typeText;
    },
    // 格式化日期
    formatDate(date) {
      let dateText = '';
      // 消息日期
      let dateYMD = date.split(' ')[0]; //年月日
      let dateYear = dateYMD.split('-')[0]; //消息日期-年
      let dateMonth = dateYMD.split('-')[1]; //消息日期-月
      let dateDay = dateYMD.split('-')[2]; //消息日期-日
      let dateHMS = date.split(' ')[1]; //时分秒
      let dateHour = dateHMS.split(':')[0]; //消息日期-时
      let dateMinutes = dateHMS.split(':')[1]; //消息日期-分

      // 当天日期
      let currentDate = new Date();
      let currentYear = currentDate.getFullYear() + '';
      let currentMonth = currentDate.getMonth() + 1 + '';
      currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
      let currentDay = currentDate.getDate() + '';
      currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
      let currentYMD = `${currentYear}-${currentMonth}-${currentDay}`;

      if (dateYear === currentYear) {
        // 当年
        if (dateYMD === currentYMD) {
          // 当天
          dateText = `${dateHour}:${dateMinutes}`;
        } else {
          // 非当天
          dateText = `${dateMonth}-${dateDay} ${dateHour}:${dateMinutes}`;
        }
      } else {
        // 非当年
        dateText = `${dateYMD} ${dateHour}:${dateMinutes}`;
      }

      return dateText;
    },
    // 进入消息中心
    jumpMsgCenter() {
      this.$message(this.$t('message.developmentTips'));
    },
    // 清除未读消息
    clearUnreadMsg() {
      let ids = this.unreadMsgData.map(item => {
        return item.id;
      });

      clearUnreadMessage({
        ids: ids.join(',')
      }).then(res => {
        this.$emit('updateUnreadMsgNum');
        Object.assign(this.$data, this.$options.data());
        this.getMsgList();
      });
    },
    // 关闭信息弹窗
    closeBox() {
      this.$emit('closeHeaderMask');
      this.$emit('update:msgBoxVisible', false);
    },
    // 显示信息详情
    showMsgDetailBox(item, index) {
      this.showMsgDetail = true;
      this.msgDetail = item;
      this.currentDetailDataIndex = index;
      this.readMsg(this.msgDetail.id);
      this.changeBtnState();
    },
    // 上一条
    prevFn() {
      if (this.currentDetailDataIndex >= 0) {
        this.currentDetailDataIndex--;
        this.msgDetail = this.unreadMsgData[this.currentDetailDataIndex];
        this.readMsg(this.msgDetail.id);
        this.changeBtnState();
      }
    },
    // 下一条
    nextFn() {
      if (this.currentDetailDataIndex <= this.unreadMsgData.length - 1) {
        this.currentDetailDataIndex++;
        this.msgDetail = this.unreadMsgData[this.currentDetailDataIndex];
        this.readMsg(this.msgDetail.id);
        this.changeBtnState();
      }
    },
    // 更改按钮可点击状态
    changeBtnState() {
      let lastIndex = this.unreadMsgData.length - 1;
      if (this.unreadMsgData.length > 1) {
        let index = this.currentDetailDataIndex;
        this.prevDisabled = index === 0 ? true : false;
        this.nextDisabled = index === lastIndex ? true : false;
      } else {
        this.prevDisabled = true;
        this.nextDisabled = true;
      }
    },
    // 查看消息
    readMsg(id) {
      messageDetail({
        id
      }).then(res => {});
    },
    // 关闭弹窗
    closeDialogBox() {
      this.showMsgDetail = false;
      Object.assign(this.$data, this.$options.data());
      this.getMsgList(true);
      this.$emit('updateUnreadMsgNum');
    }
  }
};
</script>

<style lang="scss" scoped>
.message-center-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .message-center-header {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 40px;
    padding: 0 15px;
    font-size: 18px;
    background-color: #fff;

    span {
      color: #303133;
    }

    i:hover {
      color: var(--color-primary);
      cursor: pointer;
    }
  }

  .message-center-box {
    width: 100%;
    height: calc(100% - 40px - 62px);
    overflow-y: auto;
  }

  .message-center-list {
    padding-bottom: 10px;
    background-color: #f5f7fa;

    li {
      width: 100%;
      margin-bottom: 10px;
      padding: 15px 20px;
      background-color: #fff;

      &:last-of-type {
        margin-bottom: 0;
      }

      &:hover {
        cursor: default;
      }

      .message-type-time-box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .message-type-box {
          display: flex;
          justify-content: space-between;
          align-items: center;

          span {
            width: 28px;
            height: 28px;
            margin-right: 10px;
            border-radius: 50%;
            overflow: hidden;
            background-color: #f2f2f2;

            &.msg-default {
              background: url('../../assets/images/msg_default.png');
            }

            &.msg-warning {
              background: url('../../assets/images/msg_warning.png');
            }

            &.msg-danger {
              background: url('../../assets/images/msg_danger.png');
            }
          }
        }

        .message-time-box {
          color: #909399;
          font-size: 13px;
        }
      }

      .message-text-box {
        line-height: 24px;
        margin-top: 10px;
        color: #909399;
        font-size: 13px;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
    }
  }

  .no-data-box {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 110px 20px 20px;
    color: #909399;
    font-size: 16px;

    img {
      width: 272px;
      height: 204px;
      margin-bottom: 30px;
    }
  }

  .message-center-footer {
    flex-shrink: 0;
    display: flex;
    gap: 20px;
    width: 100%;
    height: 62px;
    padding: 10px 20px 0;
    text-align: center;
    background-color: #fff;

    .message-center-btn {
      flex: 1;
      height: 32px;
      padding: 0;
      color: #606266;
      font-size: 12px;
      outline: none;
      border: 1px solid #e4e7ed;
      border-radius: 3px;
      background-color: transparent;

      &.active {
        color: var(--color-primary);
        border-color: var(--color-primary);
      }
    }
  }

  .message-detail-dialog {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);

    .message-detail-dialog-container {
      width: 720px;
      padding: 0 15px;
      border-radius: 4px;
      background-color: #fff;

      .detail-dialog-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 48px;

        .header-title {
          color: #303133;
          font-size: 18px;
        }

        .header-close {
          font-size: 18px;

          i:hover {
            color: var(--color-primary);
            cursor: pointer;
          }
        }
      }

      .detail-dialog-body {
        width: 100%;
        max-height: 500px;
        padding: 30px 5px;
        overflow-y: auto;

        .detail-dialog-body-header {
          display: flex;
          justify-content: space-between;
          align-items: center;

          p {
            flex: 1;
            color: #303133;
            font-size: 16px;
          }

          span {
            flex-shrink: 0;
            color: #909399;
            font-size: 13px;
          }
        }

        .detail-dialog-body-content {
          line-height: 24px;
          margin-top: 20px;
        }
      }

      .detail-dialog-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 66px;
      }
    }
  }
}
</style>
